package com.qf.mybatisplus.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.qf.mybatisplus.controller.request.JwtTokenRequest;
import com.qf.mybatisplus.entity.AppInfo;
import com.qf.mybatisplus.resultBean.Result;
import com.qf.mybatisplus.service.AppInfoService;
import com.qf.mybatisplus.utils.JwtHelper;
import com.qf.mybatisplus.utils.ToolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author zdd
 * @version 1.0
 * @return
 * @date 2023/6/1 下午4:58
 * @description
 */
@RestController
@RequestMapping("/token")
public class IndexController {
    private static final Logger log = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private AppInfoService appInfoService;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public static final String JWT_SECRET = "buUTsgjzRc0HC2UHKZwYpnScTUZI3rG";

    @GetMapping("/getToken")
    @ResponseBody
    public Result getToken(@Validated JwtTokenRequest request, HttpServletRequest httpRequest) {

        JSONObject resObj = new JSONObject();

        AppInfo appInfo = appInfoService.getById(request.getAppId());

        if (appInfo == null) {
            log.error("获取token失败：未找到该app信息");
            throw new UsernameNotFoundException(request.getAppId());
        }
//
        if(!bCryptPasswordEncoder.matches(request.getAppPwd(), String.valueOf(appInfo.getAppPwd()))){
            log.error("获取token失败：密码不匹配");
            throw new BadCredentialsException(request.getAppId());
        }
        Date expiration = DateUtil.offsetHour(new Date(), 8);
        String token = JwtHelper.createJWT(String.valueOf(appInfo.getAppId()), 1, appInfo.getAppName(), ToolUtil.getClientIp(httpRequest), "", expiration.getTime(), JWT_SECRET);

        resObj.put("token",token);
        resObj.put("expiration",expiration.getTime());
        return Result.success("成功",resObj);
    }
}
